<template>
  <div id="mygoChart" style="z-index:0;height:100%;width:100%;background-color:#000000;position: absolute;"></div>
</template>
<script>
// 在export之前
import go from 'gojs'
import { getStationInfo } from '@/api/stp'
import { getServiceNames } from './api.js'
export default {
  data() {
    return {
      colorMap: ['green', '#ebd236', 'red', '#f0a308', 'gray'],
      requireChannels: {
        //需要订阅的频道放在这里
        channels: [],
        //发出申请的组件名字放在这里
        component: 'STPStation'
      },
      stationIdMap: {},
      stationIdList: [],
      stationNameList: [],
      commsvrInfo: {},
      commsvrWirelessInfo: {},
      zdkTDCSiInfo: {},
      singleStationRows: 0, // a系或b系有几行
      stationX: 250, // 车站模块在x轴上的像素数
      stationY: 300, // 车站模块在y轴上的像素数
      A_BHeight: 100, // ab系之间间隔
      stationPerRow: 14 // 每一行放几个站
    }
  },
  mounted() {
    this.initStationIdMap()
    this.subSocketChannel()
  },
  methods: {
    init() {
      var mySelf = this
      const MAKE = go.GraphObject.make
      mySelf.myDiagram = MAKE(go.Diagram, 'mygoChart', {
        initialContentAlignment: go.Spot.Center, // 居中显示
        'undoManager.isEnabled': true, // 支持 Ctrl-Z 和 Ctrl-Y 操作
        'toolManager.hoverDelay': 100, //tooltip提示显示延时
        'toolManager.toolTipDuration': 10000, //tooltip持续显示时间
        isReadOnly: true,
        autoScale: go.Diagram.Uniform,
        'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom, //有鼠标滚轮事件放大和缩小，而不是向上和向下滚动
        scrollMargin: 0 // 默认下拖拽画布的时候边界是已最外的节点为边距，这个就是增加边距的，类似padding设置
      }) //构建gojs对象

      var colorTemplate = MAKE(
        go.Node,
        new go.Binding('location', 'loc', go.Point.parse),
        MAKE(go.Shape, 'RoundedRectangle', {
          width: 100,
          height: 50,
          fill: 'transparent'
        }),
        MAKE(
          go.Panel,
          'Horizontal',
          {
            padding: 5
          },
          MAKE(
            go.Shape,
            'Rectangle',
            {
              width: 40,
              height: 40,
              fill: 'transparent'
            },
            new go.Binding('fill', 'color')
          ),
          MAKE(
            go.Panel,
            MAKE(
              go.TextBlock,
              'Default Text',
              {
                margin: 12,
                stroke: 'white',
                font: '38px sans-serif'
              },
              new go.Binding('text', 'text')
            )
          )
        )
      )

      var serverTemplate = MAKE(
        go.Node,
        new go.Binding('location', 'loc', go.Point.parse),
        MAKE(
          go.Panel,
          'Auto',
          MAKE(
            go.Shape,
            'RoundedRectangle',
            {
              width: 250,
              height: 100,
              stroke: 'white',
              strokeWidth: 3,
              fill: 'gray'
            },
            new go.Binding('width', 'width'),
            new go.Binding('fill', 'backColor')
          ),
          MAKE(
            go.TextBlock,
            {
              text: '中心通信软件',
              stroke: 'white',
              font: '35px sans-serif',
              textAlign: 'center',
              verticalAlignment: go.Spot.Center,
              height: 100,
              width: 250,
              isMultiline: true
            },
            new go.Binding('text', 'text')
          )
        ),
        new go.Binding('fromSpot', 'fromSpot')
      )

      var groupTemplate = MAKE(
        go.Node,
        new go.Binding('location', 'loc', go.Point.parse),
        MAKE(go.Shape, 'RoundedRectangle', {
          width: this.stationX * this.stationPerRow,
          height: this.stationY * this.singleStationRows,
          stroke: 'white',
          strokeWidth: 3,
          fill: 'transparent',
          strokeDashArray: [6, 3]
        }),
        MAKE(
          go.TextBlock,
          {
            text: '',
            // margin: 12,
            stroke: 'pink',
            font: '40px sans-serif',
            textAlign: 'center',
            height: this.stationY * this.singleStationRows,
            width: this.stationX * this.stationPerRow
          },
          new go.Binding('text', 'groupText'),
          new go.Binding('verticalAlignment', 'textPosition')
        )
      )

      var XLineTemplate = MAKE(
        go.Node,
        new go.Binding('location', 'loc', go.Point.parse),
        MAKE(go.Shape, 'Rectangle', {
          width: this.stationPerRow * this.stationX,
          height: 10,
          stroke: 'green',
          strokeWidth: 1,
          fill: 'green'
        })
      )

      var YLineTemplate = MAKE(
        go.Node,
        new go.Binding('location', 'loc', go.Point.parse),
        MAKE(
          go.Shape,
          'Rectangle',
          {
            width: 5,
            height: 48,
            stroke: 'green',
            strokeWidth: 1,
            fill: 'green'
          },
          new go.Binding('stroke', 'color'),
          new go.Binding('fill', 'color')
        )
      )

      var stationTemplate = MAKE(
        go.Node,
        new go.Binding('location', 'loc', go.Point.parse),
        MAKE(
          go.Shape,
          'RoundedRectangle',
          {
            fill: 'green',
            stroke: 'white',
            strokeWidth: 2,
            angle: 0,
            height: 100,
            width: 200
          },
          new go.Binding('fill', 'backColor')
        ),
        'Auto', //Vertical,Auto,Horizontal
        MAKE(
          go.Panel,
          'Horizontal',
          {
            padding: 0
          },
          MAKE(
            go.Panel,
            'Horizontal',
            MAKE(
              go.Picture,
              {
                margin: 0,
                width: 50,
                height: 50,
                background: 'transparent',
                source: require('./station.png')
              },
              new go.Binding('source', 'img')
            )
          ),
          MAKE(go.Panel, 'Vertical', MAKE(go.TextBlock, 'Default Text', { margin: 5, stroke: 'white', font: 'bold 30px sans-serif' }, new go.Binding('text', 'stationName')), MAKE(go.TextBlock, { stroke: 'white', text: 'ZDKHost', font: '20px sans-serif' }, { margin: 5 }))
        ),
        {
          mouseEnter: function(e, node, prev) {
            // console.log('mouseEnter')
          },
          mouseLeave: function(e, node, prev) {
            mySelf.detailShow = false
          }
        }
      )

      mySelf.myDiagram.nodeTemplateMap.add('station', stationTemplate)
      mySelf.myDiagram.nodeTemplateMap.add('xline', XLineTemplate)
      mySelf.myDiagram.nodeTemplateMap.add('yline', YLineTemplate)
      mySelf.myDiagram.nodeTemplateMap.add('group', groupTemplate)
      mySelf.myDiagram.nodeTemplateMap.add('server', serverTemplate)
      mySelf.myDiagram.nodeTemplateMap.add('color', colorTemplate)

      const serverLinkTemplate = MAKE(
        go.Link,
        {
          routing: go.Link.Orthogonal, // Orthogonal routing
          corner: 10, // with rounded corners
          fromSpot: go.Spot.Right,
          toSpot: go.Spot.Left
        },
        MAKE(go.Shape, {
          stroke: 'green',
          strokeWidth: 11
        })
      )

      mySelf.myDiagram.linkTemplateMap.add('serverLink', serverLinkTemplate)

      this.initStationNode()
      this.initXlineNode()
      this.initYlineNode() // 车站的小棍，host是上，standby是下
      this.initServerNode()
      this.initLink()
      this.initColorNode() // 颜色示例
    },
    initStationIdMap() {
      this.stationIdList = []
      getServiceNames().then(response => {
        if (response.code === 0) {
          console.log(response, 'res')
          var map = new Map()
          response.data.forEach(ele => {
            this.stationNameList.push(ele.name)
            // map.set(ele.id, ele.name + ele.type)
            map.set(ele.id, ele.name + ele.type)
          })
          this.stationIdMap = map
          this.singleStationRows = Math.ceil(this.stationNameList.length / this.stationPerRow)
          // this.stationIdList = response.data.center.hostControl.arrangeInfo
          // if (this.stationIdList.length > 0) {
          //   var map = new Map()
          //   this.stationIdList.forEach(element => {
          //     this.stationNameList.push(element.station.toString())
          //     map.set(element.entitys[0].id, (element.station.toString() + element.entitys[0].type.toString()).toString())
          //     map.set(element.entitys[1].id, (element.station.toString() + element.entitys[1].type.toString()).toString())
          //   })
          //   this.stationIdMap = map
          //   this.singleStationRows = Math.ceil(this.stationNameList.length/this.stationPerRow)
          // }
          // this.commsvrInfo = response.data.center.commsvr
          // this.commsvrWirelessInfo = response.data.center.commsvrWireless
          // this.zdkTDCSiInfo = response.data.center.zdkTDCSi
          this.init()
        } else {
          this.$message.error(response.msg)
        }
      })
      // .catch((error => {
      //   this.$message.error("未获取到中心初始数据，初始化失败")
      //   console.log(error);
      // }))
    },
    initStationNode() {
      var mySelf = this
      let stationList = this.stationNameList
      let stationRows = this.singleStationRows
      for (let i = 0; i < stationRows; i++) {
        for (let j = 0; j < this.stationPerRow; j++) {
          if (i * this.stationPerRow + j >= this.stationNameList.length) {
            break
          }
          const stationName = stationList[j + i * this.stationPerRow]
          let nodeData_A = { key: '', stationName: '', loc: '', backColor: this.colorMap[4], category: '' }
          // let nodeData_B = { key: '', stationName: '', loc: '', backColor: this.colorMap[4], category: '' }
          nodeData_A.key = stationName + 'A'
          // nodeData_B.key = stationName + 'B'
          nodeData_A.stationName = stationName
          // nodeData_B.stationName = stationName
          nodeData_A.category = 'station'
          // nodeData_B.category = 'station'
          nodeData_A.loc = (j * 250).toString() + ', ' + (i * this.stationY).toString()
          // nodeData_B.loc = (j * 250).toString() + ', ' + (i * this.stationY + stationRows * this.stationY + this.A_BHeight).toString()
          mySelf.myDiagram.model.addNodeData(nodeData_A)
          // mySelf.myDiagram.model.addNodeData(nodeData_B)
        }
      }
    },
    initXlineNode() {
      var mySelf = this
      let stationRows = this.singleStationRows
      let BinitY = stationRows * this.stationY + this.A_BHeight
      for (let i = 0; i < stationRows; i++) {
        for (let j = 0; j < 2; j++) {
          // let nodeData_host = { key: '', loc: '', category: 'xline' }
          let nodeData_standby = { key: '', loc: '', category: 'xline' }
          if (j == 0) {
            // nodeData_host.key = 'hostLine_' + (i + 1).toString()
            nodeData_standby.key = 'standbyLine_' + (i + 1).toString()
            // nodeData_host.loc = '0, ' + (i * this.stationY - 50).toString()
            nodeData_standby.loc = '-20, ' + (i * this.stationY + 150).toString()
            // mySelf.myDiagram.model.addNodeData(nodeData_host)
            mySelf.myDiagram.model.addNodeData(nodeData_standby)
          } else {
            // nodeData_host.key = 'hostLine_' + (i + 1 + stationRows).toString()
            nodeData_standby.key = 'standbyLine_' + (i + 1 + stationRows).toString()
            // nodeData_host.loc = '0, ' + (i * this.stationY - 50 + BinitY).toString()
            nodeData_standby.loc = '-20, ' + (i * this.stationY + 150 + BinitY).toString()
            // mySelf.myDiagram.model.addNodeData(nodeData_host)
            mySelf.myDiagram.model.addNodeData(nodeData_standby)
          }
        }
        // let nodeData_host = { key: '', loc: '', category: 'xline' }
        let nodeData_standby = { key: '', loc: '', category: 'xline' }
        // nodeData_host.key = 'hostLine_' + (stationRows*2 + 1).toString()
        nodeData_standby.key = 'standbyLine_' + (stationRows * 2 + 1).toString()
        // nodeData_host.loc = '0, ' + (BinitY*2 - 50).toString()
        nodeData_standby.loc = '-20, ' + (BinitY * 2 + 150).toString()
        // mySelf.myDiagram.model.addNodeData(nodeData_host)
        mySelf.myDiagram.model.addNodeData(nodeData_standby)
      }
    },
    initYlineNode() {
      var mySelf = this
      let stationList = this.stationNameList
      let stationRows = this.singleStationRows
      for (let i = 0; i < stationRows; i++) {
        for (let j = 0; j < this.stationPerRow; j++) {
          if (i * this.stationPerRow + j >= this.stationNameList.length) {
            break
          }
          const element = stationList[j + i * this.stationPerRow]
          let nodeData_A_hostLine = { key: '', loc: '', color: this.colorMap[4], category: 'yline' }
          let nodeData_A_standbyLine = { key: '', loc: '', color: this.colorMap[4], category: 'yline' }
          let nodeData_B_hostLine = { key: '', loc: '', color: this.colorMap[4], category: 'yline' }
          let nodeData_B_standbyLine = { key: '', loc: '', color: this.colorMap[4], category: 'yline' }

          nodeData_A_hostLine.key = element + 'AHostLine'
          nodeData_A_standbyLine.key = element + 'AStandbyLine'
          nodeData_B_hostLine.key = element + 'BHostLine'
          nodeData_B_standbyLine.key = element + 'BStandbyLine'

          nodeData_A_hostLine.loc = (j * 250 + 100).toString() + ', ' + (i * this.stationY - 50).toString()
          nodeData_A_standbyLine.loc = (j * 250 + 100).toString() + ', ' + (i * this.stationY + 100).toString()
          nodeData_B_hostLine.loc = (j * 250 + 100).toString() + ', ' + (i * this.stationY + stationRows * this.stationY + this.A_BHeight - 50).toString()
          nodeData_B_standbyLine.loc = (j * 250 + 100).toString() + ', ' + (i * this.stationY + stationRows * this.stationY + this.A_BHeight + 100).toString()

          // mySelf.myDiagram.model.addNodeData(nodeData_A_hostLine)
          mySelf.myDiagram.model.addNodeData(nodeData_A_standbyLine)
          // mySelf.myDiagram.model.addNodeData(nodeData_B_hostLine)
          // mySelf.myDiagram.model.addNodeData(nodeData_B_standbyLine)
        }
      }
    },
    initServerNode() {
      var mySelf = this
      var commsvrGap = 200 // commsvr离车站的距离
      var serverWidth = 300 // 方块的宽
      var commsvrY = this.stationY * this.singleStationRows
      var commsvrB_X = this.stationX * this.stationPerRow + commsvrGap
      var commsvrA_X = (serverWidth + commsvrGap) * -1

      mySelf.myDiagram.model.addNodeData({ key: 'groupA', loc: '-25, -150', groupText: '跟踪控车服务器A', category: 'group' })
      // mySelf.myDiagram.model.addNodeData({ key: 'groupB', loc: '-25, ' + (commsvrY + this.A_BHeight).toString(), groupText: '跟踪控车服务器B', textPosition: go.Spot.Bottom, category: 'group' })

      // mySelf.myDiagram.model.addNodeData({ key: String(this.commsvrInfo.entitys[0].id), loc: commsvrA_X.toString() + ', ' + commsvrY.toString(), width: serverWidth, text: this.commsvrInfo.softwareName + this.commsvrInfo.entitys[0].type, category: 'server' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.commsvrInfo.entitys[1].id), loc: commsvrB_X.toString() + ', ' + commsvrY.toString(), width: serverWidth, text: this.commsvrInfo.softwareName + this.commsvrInfo.entitys[1].type, category: 'server' })

      var softwaresY = (this.A_BHeight + this.singleStationRows * this.stationY) * 2
      var softwaresX = this.stationX * this.stationPerRow
      var softwareX = Math.ceil(softwaresX / 2)
      var zdkX = Math.ceil(softwareX / 2)
      var commsvrWirelessX = Math.ceil((softwaresX / 2) * 1.5)
      var softwareOffset = 500
      // mySelf.myDiagram.model.addNodeData({ key: String(this.zdkTDCSiInfo.entitys[0].id), loc: zdkX.toString() + ', ' + softwaresY.toString(), width: serverWidth, text: this.zdkTDCSiInfo.softwareName + this.zdkTDCSiInfo.entitys[0].type, category: 'server' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.zdkTDCSiInfo.entitys[1].id), loc: (zdkX - softwareOffset).toString() + ', ' + softwaresY.toString(), width: serverWidth, text: this.zdkTDCSiInfo.softwareName + this.zdkTDCSiInfo.entitys[1].type, category: 'server' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.commsvrWirelessInfo.entitys[0].id), loc: commsvrWirelessX.toString() + ', ' + softwaresY.toString(), width: serverWidth, text: this.commsvrWirelessInfo.softwareName + this.commsvrWirelessInfo.entitys[0].type, category: 'server' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.commsvrWirelessInfo.entitys[1].id), loc: (commsvrWirelessX - softwareOffset).toString() + ', ' + softwaresY.toString(), width: serverWidth, text: this.commsvrWirelessInfo.softwareName + this.commsvrWirelessInfo.entitys[1].type, category: 'server' })
      console.log('81192');
      
      var ylineOffsetX = 150
      var ylineOffsetY = 103
      // mySelf.myDiagram.model.addNodeData({ key: String(this.zdkTDCSiInfo.entitys[0].id) + 'StandbyLine', loc: (zdkX + ylineOffsetX).toString() + ', ' + (softwaresY + ylineOffsetY).toString(), color: this.colorMap[4], category: 'yline' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.zdkTDCSiInfo.entitys[1].id) + 'StandbyLine', loc: (zdkX - softwareOffset + ylineOffsetX).toString() + ', ' + (softwaresY + ylineOffsetY).toString(), color: this.colorMap[4], category: 'yline' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.commsvrWirelessInfo.entitys[0].id) + 'StandbyLine', loc: (commsvrWirelessX + ylineOffsetX).toString() + ', ' + (softwaresY + ylineOffsetY).toString(), color: this.colorMap[4], category: 'yline' })
      // mySelf.myDiagram.model.addNodeData({ key: String(this.commsvrWirelessInfo.entitys[1].id) + 'StandbyLine', loc: (commsvrWirelessX - softwareOffset + ylineOffsetX).toString() + ', ' + (softwaresY + ylineOffsetY).toString(), color: this.colorMap[4], category: 'yline' })
    },
    initLink() {
      var mySelf = this
      var linkLineNums = (this.singleStationRows + 1) * 2
      for (let index = 1; index < linkLineNums; index++) {
        // let linkData_host = { from: '', to: '', category: '' }
        let linkData_standby = { from: '', to: '', category: '' }
        // linkData_host.from = String(this.commsvrInfo.entitys[1].id)
        // linkData_standby.from = String(this.commsvrInfo.entitys[0].id)
        // linkData_host.to = 'hostLine_' + index.toString()
        linkData_standby.to = 'standbyLine_' + index.toString()
        // linkData_host.category = 'serverLink'
        linkData_standby.category = 'serverLink'
        // mySelf.myDiagram.model.addLinkData(linkData_host)
        mySelf.myDiagram.model.addLinkData(linkData_standby)
      }
    },
    initColorNode() {
      var mySelf = this
      let topHeight = (this.singleStationRows * this.stationY + this.A_BHeight) * 2 + 300
      let colorList = ['green', '#ebd236', 'red', '#f0a308', 'gray']
      let textList = ['设备正常状态', '设备备用状态', '设备离线状态', '设备未使用状态', '设备未知状态']
      for (let index = 0; index < 5; index++) {
        let node = { key: '', color: '', loc: '0, 0', text: '', category: 'color' }
        node.key = textList[index] + '_color'
        node.text = textList[index]
        node.color = colorList[index]
        node.loc = (360 * index).toString() + ', ' + topHeight.toString()
        mySelf.myDiagram.model.addNodeData(node)
      }
    },
    subSocketChannel() {
      this.requireChannels.channels.push('STP2.0_Center_MaintainState')
      //向全局申请订阅频道（订阅请求，订阅信息）
      this.$bus.$emit('Subscribe', this.requireChannels)

      // 接收数据
      this.sockets.subscribe('STP2.0_Center_MaintainState', res => {
        var key = res.data.softId
        // if (key == this.commsvrInfo.entitys[1].id) {
        //   if (res.data.states.net[this.commsvrInfo.entitys[0].id] == 0) {
        //     this.refreshStationStatus(key.toString(), this.colorMap[3])
        //   } else {
        //     this.refreshStationStatus(key.toString(), this.colorMap[0])
        //   }
        // }
        // if (key == this.commsvrInfo.entitys[0].id) {
        //   if (res.data.states.net[this.commsvrInfo.entitys[0].id] == 0) {
        //     this.refreshStationStatus(key.toString(), this.colorMap[2])
        //   } else {
        //     this.refreshStationStatus(key.toString(), this.colorMap[0])
        //   }
        // }
        // if (key == this.zdkTDCSiInfo.entitys[1].id) {
        //   if (res.data.states.net[this.zdkTDCSiInfo.entitys[0].id] == 0) {
        //     this.refreshStationStatus(key.toString(), this.colorMap[3])
        //   } else {
        //     this.refreshStationStatus(key.toString(), this.colorMap[0])
        //   }
        // }
        // if (key == this.zdkTDCSiInfo.entitys[0].id) {
        //   if (res.data.states.net[this.zdkTDCSiInfo.entitys[0].id] == 0) {
        //     this.refreshStationStatus(key.toString(), this.colorMap[2])
        //   } else {
        //     this.refreshStationStatus(key.toString(), this.colorMap[0])
        //   }
        // }
        // if (key == this.commsvrWirelessInfo.entitys[1].id) {
        //   if (res.data.states.net[this.commsvrWirelessInfo.entitys[0].id] == 0) {
        //     this.refreshStationStatus(key.toString(), this.colorMap[3])
        //   } else {
        //     this.refreshStationStatus(key.toString(), this.colorMap[0])
        //   }
        // }
        // if (key == this.commsvrWirelessInfo.entitys[0].id) {
        //   if (res.data.states.net[this.commsvrWirelessInfo.entitys[0].id] == 0) {
        //     this.refreshStationStatus(key.toString(), this.colorMap[2])
        //   } else {
        //     this.refreshStationStatus(key.toString(), this.colorMap[0])
        //   }
        // }
        if (this.stationIdMap.get(key)) {
          if (res.data.states.net.hasOwnProperty(key)) {
            if (res.data.states.net[key] == 0) {
              this.refreshStationStatus(this.stationIdMap.get(key), this.colorMap[2])
            } else {
              this.refreshStationStatus(this.stationIdMap.get(key), this.colorMap[0])
            }
          }
        }
      })
    },
    refreshStationStatus(stationName, color) {
      var mySelf = this
      let station = mySelf.myDiagram.model.findNodeDataForKey(stationName)
      let hostYLine = mySelf.myDiagram.model.findNodeDataForKey(stationName + 'HostLine')
      let standbyYLine = mySelf.myDiagram.model.findNodeDataForKey(stationName + 'StandbyLine')
      mySelf.myDiagram.model.setDataProperty(station, 'backColor', color)
      mySelf.myDiagram.model.setDataProperty(hostYLine, 'color', color)
      mySelf.myDiagram.model.setDataProperty(standbyYLine, 'color', color)
    }
  }
}
</script>
<style lang="scss">
// .main-container {
//   height: 100%;

//   .app-main {
//     height: 88%;

//     #mygoChart {
//       height: 100%;
//     }
//   }
//   color: #9be837c9;
// }
.el-range-separator {
  width: 24px;
}

::-webkit-scrollbar {
  width: 8px;
  /*滚动条宽度*/
  height: 8px;
  /*滚动条高度*/
}

::-webkit-scrollbar-track {
  border-radius: 0px;
  /*滚动条的背景区域的圆角*/
  background-color: rgba(2, 29, 87, 1);
  /*滚动条的背景颜色*/
}

::-webkit-scrollbar-corner {
  background-color: rgba(2, 29, 87, 1);
}

::-webkit-scrollbar-thumb {
  border-radius: 4px;
  /*滚动条的圆角*/
  background-color: rgba(10, 75, 139, 0.5);
  /*滚动条的背景颜色*/
}

html,
body,
#app {
  height: 100%;
}
</style>
